#!coding:utf-8

from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_protect, csrf_exempt

import uuid

from py2neo import Node, Relationship, NodeSelector
from GraphDB import graphDB


def index(request):
    return render(request, 'index.html')

## 如果没有csrf.js, 可以用这个标记禁用csrf检测
#@csrf_exempt
def objectTypeAdd(request):
    title = request.POST['objectTypeTitle']
    color = request.POST['objectTypeColor']
    desc = request.POST['objectTypeDesc']

    tx = graphDB.begin()
    objectType = Node('ObjectType')
    ## 借由uuid库生成节点唯一ID
    ## 注意:uuidx()函数生成的结果为UUID类复杂类型, 需要转换成字符串简单类型
    objectType['uuid'] = str(uuid.uuid1())
    objectType['title'] = title
    objectType['color'] = color
    objectType['desc'] = desc
    tx.create(objectType)

    manageTree = graphDB.find_one('META', 'title', 'management')
    list = Relationship(manageTree, 'list', objectType)
    ## 这里为"联系"对象也创建id属性
    list['uuid'] = str(uuid.uuid1())
    tx.create(list)
    tx.commit()

def objectTypeList(request):
    ## 查询操作不使用Transaction对象
    selector = NodeSelector(graphDB)
    result = selector.select('ObjectType')
    ## 注意: select()方法返回的原始对象格式是包括节点id在内的
    ## 需要使用list()方法将其转换成数组形式才能以json格式返回给客户端.
    ## print(result)
    print(result)
    result = {'result': list(result)}
    return JsonResponse(result)

def overview(request):
    ## result: 结果集
    result = {'nodes': {}, 'relations': {}}
    root = graphDB.find_one('META', 'uuid', '248f992a-8bbf-11e6-99b5-0242ac110002')
    ## match()函数的结果是一个`generator`类型
    tree = graphDB.match(start_node=root)
    ## print(type(tree))
    ## print(tree)

    ## 如果tree中只有一个management根节点, for循环就不会执行.
    ## 也就是说, match返回的必然都是Relationship类型, 孤岛节点不会出现.
    for leaf in tree:
        ## 每一行结果都是一个Relationship类型
        print(type(leaf))
        ## 分别得到Relationship的名称(字符串), 左侧与右侧节点(对象)
        print(leaf.type())
        print(leaf.start_node())
        print(leaf.end_node())

        start, end = dict(leaf.start_node()), dict(leaf.end_node())
        startID, endID = start['uuid'], end['uuid']

        if not result['nodes'].has_key(startID):
            result['nodes'][start['uuid']] = start
        if not result['nodes'].has_key(endID):
            result['nodes'][end['uuid']] = end

        relationID = leaf['uuid']
        if not result['relations'].has_key(relationID):
            result['relations'][relationID] = {
                'uuid': leaf['uuid'],
                'name': leaf.type(),
                'source': startID,
                'target': endID
            }
    return JsonResponse(result)